package com.formula.distribution.idempotent.utils;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 封装的redis工具类
 *
 * @author yang yang
 * @create 2018/12/10
 */
@Component
public class RedisUtils {

    private static final long timeOut = 60 * 60;

    /**
     * 校验redis是否存在该key
     *
     * @param key
     * @return
     */
    public boolean exist(StringRedisTemplate redisTemplate, String key) {
        return redisTemplate.hasKey(key);
    }

    /**
     * 判断redis中是否存在且是否存在值
     *
     * @param key
     * @return
     */
    public boolean existValue(StringRedisTemplate redisTemplate, String key) {
        String value = redisTemplate.opsForValue().get(key);
        //判断redis中是否存在且是否存在值
        if (StringUtils.isEmpty(value)) {
            return false;
        }
        //移除该key
        redisTemplate.expire(key, 0, TimeUnit.MILLISECONDS);
        return true;
    }

    public String getToken(StringRedisTemplate redisTemplate, String key) {
        String token = key + System.currentTimeMillis();
        redisTemplate.opsForValue().set(token, token, timeOut, TimeUnit.SECONDS);
        return token;
    }

}